<template>
    <div class="new_main">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item required prop="username">
          <a-input v-model="model.username" size="large" placeholder="请输入帐户名 ">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input>
        </a-form-model-item>
        <a-form-model-item required prop="password">
          <a-input v-model="model.password" size="large" :type="pwdType" autocomplete="false" placeholder="请输入密码 ">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            <a-icon slot="prefix" :type="pwdIconType" style="position: absolute;left: 238px;font-size: 20px;" @click="pwd" :style="{ color: 'rgba(0,0,0,.25)' }"/>
          </a-input>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="14">
            <a-form-model-item required prop="inputCode">
              <a-input v-model="model.inputCode" size="large" :max-length="4"  type="text" placeholder="图形验证码">
                <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" style="text-align: right">
            <img v-if="requestCodeSuccess" style="margin-top: 2px; height: 37px; width: 105px;border-radius: 3px;cursor: pointer;" :src="randCodeImage" @click="handleChangeCheckCode"/>
            <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
          </a-col>
        </a-row>

<!--        <a-row :gutter="0">
          <a-col :span="14">
            <a-form-model-item required prop="captcha">
              <a-input v-model="model.captcha" size="large" :max-length="6" type="text" placeholder="短信验证码">
                <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" style="padding-left: 8px; padding-right: 8px;" >
            <a-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"></a-button>
          </a-col>
        </a-row>-->


      </a-form-model>
    </div>
</template>

<script>
  import { getAction,postAction } from '@/api/manage'
  import Vue from 'vue'
  import { mapActions } from 'vuex'

  export default {
    name: 'LoginAccount',
    data(){
      return {
        pwdType:'password',
        pwdIconType:'eye-invisible',
        requestCodeSuccess: false,
        randCodeImage: '',
        currdatetime: '',
        loginType: 0,
        model:{
          username: '',
          password: '',
          inputCode: '',
          captcha:'',
        },
        state: {
          time: 60,
          smsSendBtn: false,
        },
        validatorRules:{
          username: [
            { required: true, message: '请输入用户名!' },
            { validator: this.handleUsernameOrEmail }
          ],
          password: [{
            required: true, message: '请输入密码!', validator: 'click'
          }],
         /* captcha: [
            { required: true, message: '请输入短信验证码!' }
          ],*/
          inputCode: [{
            required: true, message: '请输入图形验证码!'
          }]
        }

      }
    },
    created() {
      this.handleChangeCheckCode();
    },
    methods:{
      ...mapActions(['Login']),
      /**刷新验证码*/
      handleChangeCheckCode(){
        this.currdatetime = new Date().getTime();
        this.model.inputCode = ''
        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            this.randCodeImage = res.result
            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })
      },
      pwd(){
        if(this.pwdIconType=='eye'){
          this.pwdIconType='eye-invisible';
          this.pwdType="password";
        }else{
          this.pwdIconType='eye';
          this.pwdType="text";
        }
      },
      // 判断登录类型
      handleUsernameOrEmail (rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      /**
       * 验证字段
       * @param arr
       * @param callback
       */
      validateFields(arr, callback){
        let promiseArray = []
        for(let item of arr){
          let p = new Promise((resolve, reject) => {
            this.$refs['form'].validateField(item, (err)=>{
              if(!err){
                resolve();
              }else{
                reject(err);
              }
            })
          });
          promiseArray.push(p)
        }
        Promise.all(promiseArray).then(()=>{
          callback()
        }).catch(err=>{
          callback(err)
        })
      },
      acceptUsername(username){
        this.model['username'] = username
      },
      //账号密码登录
      handleLogin(rememberMe){
        this.validateFields([ 'username', 'password', 'inputCode'], (err)=>{
          if(!err){
            let loginParams = {
              username: this.model.username,
              password: this.model.password,
              captcha: this.model.inputCode,
              inputCode: this.model.captcha,
              checkKey: this.currdatetime,
              remember_me: rememberMe,
            }
            console.log("登录参数", loginParams)
            this.Login(loginParams).then((res) => {
              this.$emit('success', res.result)
            }).catch((err) => {
              this.$emit('fail', err)
            });
          }else{
            this.$emit('validateFail')
          }
        })
      },

      //获取验证码
/*      getCaptcha (e) {
        e.preventDefault();
        let that = this;
        that.validateFields([ 'username',"inputCode" ], (err) => {
            if (!err) {
              that.state.smsSendBtn = true;
              let interval = window.setInterval(() => {
                if (that.state.time-- <= 0) {
                  that.state.time = 60;
                  that.state.smsSendBtn = false;
                  window.clearInterval(interval);
                }
              }, 1000);
              const hide = that.$message.loading('短信验证码发送中..', 0);
              let smsParams = {};
                smsParams.mobile=that.model.username;
                smsParams.checkKey = that.currdatetime,
                smsParams.inputCode = that.model.inputCode,
              //smsParams.mobile="15952202811";
                smsParams.smsmode="0";
              postAction("/sys/sms",smsParams)
                .then(res => {
                  if(!res.success){
                    setTimeout(hide, 0);
                    clearInterval(interval);
                    that.state.time = 60;
                    that.state.smsSendBtn = false;
                    that.cmsFailed(res.message);
                  }
                  if(res.success){
                    that.$emit('senSucess', res.message)
                  }
                  setTimeout(hide, 500);
                })
                .catch(err => {
                  setTimeout(hide, 1);
                  clearInterval(interval);
                  that.state.time = 60;
                  that.state.smsSendBtn = false;
                  that.requestFailed(err);
                });
            }
          }
        );
      },*/
      cmsFailed(err){
        this.$notification[ 'error' ]({
          message: '获取验证码失败',
          description:err,
          duration: 4,
        });
      },


    }

  }
</script>

<style lang="less" scoped>
  .new_main{
    width: 280px;
    margin: 0 auto;
    img{
      margin-left: 10px;
    }
  }

  .getCaptcha{
    display: block;
    height: 40px;
  }
</style>